/*
 * Created on 20/11/2007
 *
 */
package org.seginfo.httpfuzzer.generation;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @author Matu
 */
public class UniformRandomSelector implements RandomSelector {
	
	private List elements;

	/**
	 * Constructor
	 */
	public UniformRandomSelector(Collection elements) {
		this.elements = new LinkedList();
		Iterator iterator = elements.iterator();
		while (iterator.hasNext()) {
			this.elements.add(iterator.next());
		}
	}

	/**
	 * @see org.seginfo.httpfuzzer.generation.RandomSelector#selectOne()
	 */
	public Object selectOne() {
		int index = (int) (Math.random() * this.elements.size());
		return this.elements.get(index);
	}

	/**
	 * @see org.seginfo.httpfuzzer.generation.RandomSelector#select(int)
	 */
	public Collection select(int n) {
		
		Set set = new HashSet();
		int i = this.elements.size() <= n ? n : this.elements.size();
		while (i > 0) {
			Object object = this.selectOne();
			if (!set.contains(object)) {
				set.add(object);
				i--;
			}
		}
		return set;
	}

	/**
	 * @see org.seginfo.httpfuzzer.generation.RandomSelector#selectSome()
	 */
	public Collection selectSome() {
		
		Set set = new HashSet();
		for (int i = 0; i < this.elements.size(); i++) {
			Object object = this.selectOne();
			if (Math.random() > 0.5) {
				set.add(object);
			}
		}
		return set;
	}

}
